import ComponentBase from "../engine/ComponentBase";
import { RingModel } from "../game/model/RingModel";
import { SocketClient } from "../net/SocketClient";


const { ccclass, property } = cc._decorator;

@ccclass
export default class RingPrefab extends ComponentBase {

    public static instance: RingPrefab = null
    private ringBg: cc.Node;

    private txtRing: cc.RichText;

    private isPlaying: boolean = false;
    // private str: string = "恭喜<color=#00b0f0>我是路人甲</color>在<color=#ff0000>红中麻将</color>游戏中胡<color=#ff0000>“四暗刻”</color>赢得<color=#ffc000>100000</color>金币"
    private initX: number = 930;
    private lastX: number = 930
    private lastModel: RingModel

    onEnable() {
        super.onEnable();
        this.ringBg = this.findChild(this.node, "ringBg")
        this.ringBg.active = false;
        if (RingPrefab.instance) {
            if (RingPrefab.instance.isPlaying) {
                this.lastModel = RingPrefab.instance.lastModel;
                this.lastX = RingPrefab.instance.lastX;
            }
        }
        RingPrefab.instance = this
        this.txtRing = this.getChild(this.node, "mask/txtRing", cc.RichText)
        if (!this.lastModel) {
            this.lastModel = RingModel.getPlayRing()
        }
        if (this.lastModel) {
            this.play(this.lastModel, this.lastX)
        }
        // SocketClient.req_notice()
    }

    //开始播放
    public startPlay() {
        if (!this.lastModel) {
            this.lastModel = RingModel.getPlayRing()
            if(this.lastModel){
                this.play(this.lastModel, this.initX)
            }
        }
    }

    private play(model: RingModel, initX: number) {
        this.lastModel = model;
        this.isPlaying = true;
        this.txtRing.node.x = initX;
        this.txtRing.string = model.desc;
    }

    private checkNextPlay() {
        this.lastModel = RingModel.getPlayRing()
        if (this.lastModel) {
            this.play(this.lastModel, this.initX)
        }
    }

    update() {
        if (this.isPlaying) {
            this.ringBg.active = true;
            this.txtRing.node.x -= 3;
            this.lastX = this.txtRing.node.x
            let rightX: number = this.txtRing.node.x + this.txtRing.node.width
            if (rightX <= 0) {
                this.isPlaying = false;
                this.txtRing.node.x = this.initX;
                RingModel.checkDeletePlay(this.lastModel)
                this.lastModel = null
                this.checkNextPlay()
            }
        } else {
            this.ringBg.active = false;
            this.txtRing.string = ""
            this.checkNextPlay()
        }
    }
}
